﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Business;
using EntitiesTM;
using System.Data;
using System.Globalization;

namespace TimeWork
{
    public partial class TimeDay : System.Web.UI.Page
    {

        public void SetCookie(string name, string value, int expireDays)
        {
            HttpCookie cookie = new HttpCookie(name);
            cookie.Value = value;
            cookie.Expires = DateTime.Now.AddDays(expireDays);
            Response.Cookies.Add(cookie);
        }

        public HttpCookie GetCookie(string name)
        {
            return Request.Cookies[name];
        }

        public void DelCookies(string name)
        {
            HttpCookie cookie = new HttpCookie(name, "");
            cookie.Expires = DateTime.Now.AddDays(-1);
            Response.Cookies.Add(cookie);
        }

        //public static DateTime dateRegister = DateTime.Now;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["email"] != null)
            {
                lblError.Text = String.Empty;
                if (!IsPostBack)
                {
                    //dateRegister = DateTime.Now;
                    SetCookie("timereg", DateTime.Now.ToString(), 30);
                    Calendar.SelectedDate = DateTime.Now;
                    fillInformation();
                    //BindDdlProject();
                    //BindDdlActivity(Int32.Parse(ddlProject.SelectedValue));
                    BindDdlCode1();   
                    
                    BindDdlTypeTime();
                    fillGrid();
                }
            }
            
        }
        private void ClearControl()
        {
            ddlHour.SelectedValue = "0";
            ddlMinute.SelectedValue = "0";
            ddlTypeTime.SelectedValue = "1";
            txtDescription.Text = String.Empty;
        }

        private void BindDdlTypeTime()
        {
            ddlTypeTime.DataSource = BuProject.selAllTypeTime(Session["companyid"].ToString());
            ddlTypeTime.DataTextField = "TypeTimeName";
            ddlTypeTime.DataValueField = "TypeTimeID";
            ddlTypeTime.DataBind();
        }


        private void BindDdlCode4(int projectID)
        {
            EnProject project = new EnProject();
            project.projectID = projectID;
            ddlCode4.DataSource = BuProject.selActivityByProjectExceptID(project, Session["companyid"].ToString());
            ddlCode4.DataTextField = "ActivityName";
            ddlCode4.DataValueField = "ActivityID";
            ddlCode4.DataBind();
        }

        private void BindDdlCode1()
        {
            ddlCode1.DataSource = BuProject.selProjectRegisterTmp(lblEmail.Text, 1, 0, Session["companyid"].ToString());
            ddlCode1.DataTextField = "ProjectName";
            ddlCode1.DataValueField = "ProjectID";
            ddlCode1.DataBind();
            ddlCode1.Items.Insert(0, new ListItem("--- Chọn sản phẩm ---", "0"));
            //ddlCode1.SelectedValue = "0";

        }
        private void BindDdlCode2(int parentID)
        {
            ddlCode2.DataSource = BuProject.selProjectRegisterTmp(lblEmail.Text, 2, parentID, Session["companyid"].ToString());
            ddlCode2.DataTextField = "ProjectName";
            ddlCode2.DataValueField = "ProjectID";
            ddlCode2.DataBind();
            ddlCode2.Items.Insert(0, new ListItem("--- Chọn sản phẩm ---", "0"));
            ddlCode2.SelectedValue = "0";
        }
        private void BindDdlCode3(int parentID)
        {
            ddlCode3.DataSource = BuProject.selProjectRegisterTmp(lblEmail.Text, 3, parentID, Session["companyid"].ToString());
            ddlCode3.DataTextField = "ProjectName";
            ddlCode3.DataValueField = "ProjectID";
            ddlCode3.DataBind();
            ddlCode3.Items.Insert(0, new ListItem("--- Chọn sản phẩm ---", "0"));
            ddlCode3.SelectedValue = "0";
        }
        //private void BindDdlActivity(int projectID)
        //{
        //    EnProject project = new EnProject();
        //    project.projectID = projectID;
        //    ddlActivity.DataSource = BuProject.selActivityByProjectExceptID(project);
        //    ddlActivity.DataTextField = "ActivityName";
        //    ddlActivity.DataValueField = "ActivityID";
        //    ddlActivity.DataBind();
        //}

        //protected void ddlProject_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    string itemSelected = ddlProject.SelectedValue;
        //    BindDdlActivity(Int32.Parse(itemSelected));  
        //}

        private void fillInformation()
        {
            if (Session["email"] != null)
            {
                string email = Session["email"].ToString();
                //EnStaff staff = BuStaff.GetStaffByEmailOpt(email);
                //lblName.Text = staff.staffName;
                lblEmail.Text = email;
            }
        }

        private void fillGrid()
        {
            gvRegisterDay.Visible = false;
            //gvRegisterDayFinish.Visible = false;

            lblError.Text = String.Empty;
            if (Session["email"] != null)
            {
                //DateTime dateRegister = DateTime.Parse(GetCookie("timereg").Value);
                DateTime dateRegister = Calendar.SelectedDate;
                lblDateRegister.Text = dateRegister.ToString("dddd, dd/MM/yyyy", new CultureInfo("vi-VN"));
                //int check = BuTimeDay.checkRegisterDay(dateRegister.ToString(), Session["email"].ToString());
                //if (check == 0)
                //{
                    pnlAction.Visible = true;
                    //cbFinishRegister.Checked = false;
                    gvRegisterDay.Visible = true;

                    DataTable table = BuTimeDay.selRegisterDay(dateRegister.ToString(), Session["email"].ToString(), Session["companyid"].ToString());
                    gvRegisterDay.DataSource = table;
                    gvRegisterDay.DataBind();
                //}
                //else
                //{
                //    pnlAction.Visible = false;
                //    //cbFinishRegister.Checked = true;
                //    gvRegisterDayFinish.Visible = true;

                //    DataTable table = BuTimeDay.selRegisterDay(dateRegister.ToString(), Session["email"].ToString());
                //    gvRegisterDayFinish.DataSource = table;
                //    gvRegisterDayFinish.DataBind();

                //}
            }

        }

        protected void gvRegisterDay_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gvRegisterDay.EditIndex = e.NewEditIndex;
            fillGrid();
        }

        protected void gvRegisterDay_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvRegisterDay.EditIndex = -1;
            fillGrid();
        }

        protected void gvRegisterDay_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            EnSA sa = new EnSA();
            try
            {
                string timeTmp = ((TextBox)gvRegisterDay.Rows[e.RowIndex].FindControl("txtTimeReport")).Text;
                string[] strS = timeTmp.Split(':');
                sa.saTimeReportHour = Int32.Parse(strS[0]);
                sa.saTimeReportMinute = Int32.Parse(strS[1]);
                sa.saDetails = ((TextBox)gvRegisterDay.Rows[e.RowIndex].FindControl("txtDescription")).Text;
                sa.saID = Int32.Parse(gvRegisterDay.DataKeys[e.RowIndex].Values[0].ToString());
                sa.saTypeTimeID = Int32.Parse(((DropDownList)gvRegisterDay.Rows[e.RowIndex].FindControl("ddlTypeTimeName")).SelectedValue);
                BuTimeDay.updRegisterDay(sa, Session["companyid"].ToString());
            }
            catch { }

            gvRegisterDay.EditIndex = -1;
            fillGrid();
        }

        protected void gvRegisterDay_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
             EnSA sa = new EnSA();
             try
             { 
                 sa.saID = Int32.Parse(gvRegisterDay.DataKeys[e.RowIndex].Values[0].ToString());
                 BuTimeDay.delRegisterDay(sa, Session["companyid"].ToString());
             }
             catch { }
             fillGrid();
        }

        private int totalHour = 0;
        private int totalMinute = 0;
        protected void gvRegisterDay_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                TextBox txtTimeReport = (TextBox)e.Row.FindControl("txtTimeReport");
                if (txtTimeReport != null)
                {
                    int saID = Int32.Parse(gvRegisterDay.DataKeys[e.Row.RowIndex].Values[0].ToString());
                    EnSA sa = BuTimeDay.selRegisterByID(saID, Session["companyid"].ToString());
                    txtTimeReport.Text = sa.saTimeReportHour + ":" + sa.saTimeReportMinute;
                }

                totalHour += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "SAReportTimeHour"));
                totalMinute += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "SAReportTimeMinute"));

                // Fill dropdownlist khi sua bang
                DropDownList ddlTypeTimeName = (DropDownList)e.Row.FindControl("ddlTypeTimeName");
                if (ddlTypeTimeName != null)
                {
                    ddlTypeTimeName.DataSource = BuProject.selAllTypeTime(Session["companyid"].ToString());
                    ddlTypeTimeName.DataTextField = "TypeTimeName";
                    ddlTypeTimeName.DataValueField = "TypeTimeID";
                    ddlTypeTimeName.DataBind();
                    ddlTypeTimeName.SelectedValue = gvRegisterDay.DataKeys[e.Row.RowIndex].Values[1].ToString();
                    
                }
            }

            if (e.Row.RowType == DataControlRowType.Footer)
            {
                if (totalMinute >= 60)
                {
                    int addHour = totalMinute / 60;
                    totalMinute -= 60 * addHour;
                    totalHour += addHour;
                }
                Label lblSum = (Label)e.Row.FindControl("lblSum");
                lblSum.Text = totalHour.ToString() + ":" + totalMinute.ToString() + " h";

            }
        }

        protected void btnRegister_Click(object sender, EventArgs e)
        {
            EnSA sa = new EnSA();
            lblError.Text = String.Empty;

            string activityID = ddlCode4.SelectedValue;
            int hour = Int32.Parse(ddlHour.SelectedValue);
            int minute = Int32.Parse(ddlMinute.SelectedValue);
            int typeTimeID = Int32.Parse(ddlTypeTime.SelectedValue);
            bool isValidActivity = true;
            bool isValidTime = true;
            if (activityID.Equals("") || activityID.Equals("0"))
            {

                isValidActivity = false;
                lblError.Text += "* Sản phẩm này chưa đuợc phân công công việc. Hãy liên hệ với quản trị để bổ sung công việc.<br>";
            }

            if (hour == 0 && minute == 0)
            {
                isValidTime = false;
                lblError.Text += "* Thời gian đăng ký phải lớn hơn 0.<br>";
            }

            if (isValidActivity && isValidTime)
            {
                sa.saActivityID = Int32.Parse(activityID);
                sa.saTimeReportHour = hour;
                sa.saTimeReportMinute = minute;
                //sa.saDate = DateTime.Parse(GetCookie("timereg").Value);
                sa.saDate = Calendar.SelectedDate;
                sa.email = lblEmail.Text;
                sa.saDetails = txtDescription.Text;
                sa.saTypeTimeID = typeTimeID;

                BuTimeDay.insRegisterDay(sa, Session["companyid"].ToString());
                fillGrid();
                ClearControl();
            }
        }

        protected void Calendar_SelectionChanged(object sender, EventArgs e)
        {
            //dateRegister = Calendar.SelectedDate;
            SetCookie("timereg", Calendar.SelectedDate.ToString(), 30);
            fillGrid();
        }

        protected void ddlCode1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlCode2.Visible = false;
            ddlCode3.Visible = false;
            ddlCode4.Visible = false;
            if (!ddlCode1.SelectedValue.Equals("0"))
            {
                ddlCode2.Visible = true;
                BindDdlCode2(Int32.Parse(ddlCode1.SelectedValue));
            }
            else
            {
                BindDdlCode4(0);       
            }
        }

        protected void ddlCode2_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlCode2.Visible = true;
            ddlCode3.Visible = false;
            ddlCode4.Visible = false;
            if (!ddlCode2.SelectedValue.Equals("0"))
            {
                //ddlCode2.Visible = true;
                ddlCode3.Visible = true;
                BindDdlCode3(Int32.Parse(ddlCode2.SelectedValue));
            }
            else
            {
                BindDdlCode4(0);       
            }
        }

        protected void ddlCode3_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlCode2.Visible = true;
            ddlCode3.Visible = true;
            ddlCode4.Visible = false;
            if (!ddlCode3.SelectedValue.Equals("0"))
            {
                //ddlCode2.Visible = true;
                //ddlCode3.Visible = true;
                ddlCode4.Visible = true;
                BindDdlCode4(Int32.Parse(ddlCode3.SelectedValue));
            }
            else
            {
                BindDdlCode4(0);       
            }
        }

        //protected void cbFinishRegister_CheckedChanged(object sender, EventArgs e)
        //{
        //    if (Session["email"] != null)
        //    {
        //        EnSA sa = new EnSA();
        //        sa.email = Session["email"].ToString();
        //        sa.saDate = dateRegister;
        //        sa.saIsFinish = cbFinishRegister.Checked;

        //        BuTimeDay.updRegisterDayFinish(sa);
        //        fillGrid();
        //    }
        //}

        //private int totalHour1 = 0;
        //private int totalMinute1 = 0;
        //protected void gvRegisterDayFinish_RowDataBound(object sender, GridViewRowEventArgs e)
        //{
        //    if (e.Row.RowType == DataControlRowType.DataRow)
        //    {
        //        totalHour1 += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "SAReportTimeHour"));
        //        totalMinute1 += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "SAReportTimeMinute"));
        //    }

        //    if (e.Row.RowType == DataControlRowType.Footer)
        //    {
        //        if (totalMinute1 >= 60)
        //        {
        //            int addHour = totalMinute1 / 60;
        //            totalMinute1 -= 60 * addHour;
        //            totalHour1 += addHour;
        //        }
        //        Label lblSum = (Label)e.Row.FindControl("lblSum");
        //        lblSum.Text = totalHour1.ToString() + ":" + totalMinute1.ToString() + " h";

        //    }
        //}
    }
}